package cn.huaqingcheng.tool.core;

import org.jetbrains.annotations.Contract;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * IO 相关
 */
@SuppressWarnings("unused")
public interface IoTool {

    /**
     * 读取当前类路径下资源
     *
     * @param path 类路径下资源路径, 使用当前类的类加载器
     * @return 读取为字符串
     */
    static String getResourceAsStr(String path) {
        return getResourceAsStr(path, IoTool.class.getClassLoader());
    }

    /**
     * 读取指定类路径下的资源
     *
     * @param path 类路径下的资源路径, 无需前置 /
     * @param cl   使用自定义的类加载器, 以绕过模块封装
     * @throws RuntimeException     任何 IO 异常, 包装为运行时异常
     * @throws NullPointerException 如果文件不存在, 或无法访问
     * @see Module#getResourceAsStream(String)
     * @see Module#isOpen(String)
     */
    @Contract(value = "null, _ -> fail; _, null -> fail; !null, !null -> new", pure = true)
    static String getResourceAsStr(String path, ClassLoader cl) {
        try (
            InputStream is = cl.getResourceAsStream(path);
            InputStreamReader isr = new InputStreamReader(Objects.requireNonNull(is, "文件不存在/未公开/访问被拒绝"), StandardCharsets.UTF_8);
            BufferedReader br = new BufferedReader(isr)
        ) {
            StringBuilder sb = new StringBuilder(16);
            while (true) {
                String line = br.readLine();
                if (line == null) {
                    break;
                }
                sb.append(line);
            }
            return sb.toString();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
